package org.guohao.mockdata.controller;

import java.net.URL;
import java.sql.Connection;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.guohao.mockdata.constant.DBType;
import org.guohao.mockdata.entity.DBConnectEntity;
import org.guohao.mockdata.utils.JDBCUtil;
import org.guohao.mockdata.utils.SyncManager;

public class ConnectController implements Initializable {

  public DBType dbType;
  public VBox settingForm;
  public TextField connectName;
  public TextField hostName;
  public TextField port;
  public TextField username;
  public PasswordField password;
  public Button cancelBtn;

  public void setSyncManager(SyncManager syncManager) {
    this.syncManager = syncManager;
  }

  private Boolean isTest = false;
  private SyncManager syncManager;

  @Override
  public void initialize(URL location, ResourceBundle resources) {

  }

  public void test() {
    Connection conn = null;
    String jdbcUrl = "";
    switch (dbType) {
      case DM:
        jdbcUrl = "jdbc:dm://" + hostName.getText() + ":" + port.getText();
        break;
      case MYSQL:
        jdbcUrl = "jdbc:mysql://" + hostName.getText() + ":" + port.getText()
            + "?useUnicode=true&characterEncoding=utf8&serverTimezoneGMT%2B8&useSSL=true&rewriteBatchedStatements=true";
        break;
      case ORACLE:
        jdbcUrl = "jdbc:oracle:thin:@" + hostName.getText() + ":" + port.getText() + ":orcl";
        break;
    }
    try {
      conn = JDBCUtil.getConnection(dbType.getDriverName(), jdbcUrl, username.getText(),
          password.getText());
      isTest = true;
    } catch (Exception e) {
      Alert alert = new Alert(AlertType.ERROR);
      alert.setContentText(e.getMessage());
      alert.show();
    } finally {
      JDBCUtil.close(conn, null, null);
    }
  }

  public void cancel() {
    Stage stage = (Stage) cancelBtn.getScene().getWindow();
    stage.close();
  }

  public void save() {
//    if (isTest) {
      DBConnectEntity dbConnectInfo = new DBConnectEntity(connectName.getText(), dbType.name(),
          hostName.getText(), username.getText(), password.getText());
      syncManager.saveConnectSetting(dbConnectInfo);
    Stage stage = (Stage) cancelBtn.getScene().getWindow();
    stage.close();
//    } else {
//      Alert alert = new Alert(AlertType.WARNING);
//      alert.setContentText("请测试成功后保存");
//      alert.show();
//    }
  }
}